<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\MLog;
use App\Utils\GDUtil;
use Illuminate\Http\Request;
use Session;

/**
 * 后台登录控制器
 */
class LoginController extends Controller
{
    /**
     * 管理员登录页面
     */
    public function loginPage(Request $request)
    {
        return view('admin.login');
    }

    /**
     * 管理员登录处理
     */
    public function loginAct(Request $request)
    {
        if (!$this->validateReq($request, Admin::loginRulesWithMsg(0), Admin::loginRulesWithMsg(1))) {
            $this->refreshYZM();
            return back()->withInput()->withErrors($this->errors);
        } else {  //效验验证码
            if (session(GDUtil::$LOGIN_CODE) != $request->yzm) {
                $this->refreshYZM();
                $this->toast = $this->makeJsCode(1, "验证码 错误");
                return back()->with($this->toast);
            }
        }
        if ($admin = Admin::loginValid($request)) { //效验账号密码
            Session::put([
                "admin_id"    => $admin->id,
                "admin_name"  => $admin->username,
                "admin_pass"  => $admin->userpass,
                "admin_super" => $admin->super
            ]);
            $admin->refreshIP($request);
            MLog::log("管理员 $admin->username 登录系统！");
            return redirect()->route('admin.welcome');
        } else {
            $this->toast = $this->makeJsCode(1, "账号或密码错误！");
        }
        return back()->with($this->toast);
    }

    /**
     * 退出当前管理员的登陆
     */
    public function exitAct()
    {
        Session::flush();
        return redirect()->route('admin.login-page');
    }
}